package org.liurb.springboot.starter.gson.serializer;

import lombok.extern.slf4j.Slf4j;
import org.liurb.springboot.starter.gson.component.GsonManager;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.UnsupportedEncodingException;

/**
 * gson的自定义序列化
 *
 * @Author Liurb
 * @Date 2022/11/30
 */
@Slf4j
public class GsonRedisSerializer<T> implements RedisSerializer<T> {

    private Class<T> clazz;


    public GsonRedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {

        if (t == null) {
            return new byte[0];
        }

        String str = GsonManager.getInstance().toJsonText(t);
        byte[] bytes = new byte[0];
        try {

            bytes = str.getBytes("UTF-8");

        } catch (UnsupportedEncodingException e) {
            log.error("gson序列化异常", e);
        }

        return  bytes;
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {

        if (bytes == null || bytes.length <= 0) {
            return null;
        }

        String str = null;
        try {

            str = new String(bytes,"UTF-8");

        } catch (UnsupportedEncodingException e) {
            log.error("gson反序列化异常", e);
        }

        return  GsonManager.getInstance().convert(str, clazz);
    }

}
